package com.lyj.linearalgebra.user.web.servlet;

import cn.itcast.commons.CommonUtils;
import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils;
import cn.itcast.servlet.BaseServlet;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lyj.linearalgebra.user.domain.User;
import com.lyj.linearalgebra.user.service.UserException;
import com.lyj.linearalgebra.user.service.UserService;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends BaseServlet {
	
	private UserService userService = new UserService();
	
	public String regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		/*
		 * 1. 封装表单数据到form对象中
		 * 2. 补全：uid、code
		 * 3. 输入校验
		 *   > 保存错误信息、form到request域，转发到regist.jsp
		 * 4. 调用service方法完成注册
		 *   > 保存错误信息、form到request域，转发到regist.jsp
		 * 5. 发邮件
		 * 6. 保存成功信息转发到msg.jsp
		 */
		// 封装表单数据
		User form = CommonUtils.toBean(request.getParameterMap(), User.class);
		// 补全
		form.setUid(CommonUtils.uuid());
		form.setCode((String) request.getSession().getAttribute("code"));
		System.out.println(form.getCode());
		/*
		 * 输入校验
		 * 1. 创建一个Map，用来封装错误信息，其中key为表单字段名称，值为错误信息
		 */
		Map<String,String> errors = new HashMap<String,String>();
		/*
		 * 2. 获取form中的username、password、email进行校验
		 */
		String username = form.getUsername();
		if(username == null || username.trim().isEmpty()) {
			errors.put("username", "用户名不能为空！");
		} else if(username.length() < 3 || username.length() > 10) {
			errors.put("username", "用户名长度必须在3~10之间！");
		}
		
		String password = form.getPassword();
		if(password == null || password.trim().isEmpty()) {
			errors.put("password", "密码不能为空！");
		} else if(password.length() < 3 || password.length() > 10) {
			errors.put("password", "密码长度必须在3~10之间！");
		}
		
		String password1 = request.getParameter("password1");
		if(password1 == null || password1.trim().isEmpty()) {
			errors.put("password1", "密码不能为空！");
		} else if(!password1.equals(password)) {
			errors.put("password1", "两次密码不一致!");
		}
		
		String email = form.getEmail();
		if(email == null || email.trim().isEmpty()) {
			errors.put("email", "Email不能为空！");
		} else if(!email.matches("\\w+@\\w+\\.\\w+")) {
			errors.put("email", "Email格式错误！");
		}
		
		String code = (String) request.getSession().getAttribute("code");
		if(code == null || code.trim().isEmpty()) {
			errors.put("code", "验证码不能为空！");
		} else if(!code.equals(form.getCode())) {
			errors.put("code", "验证码错误！");
		}
		/*
		 * 3. 判断是否存在错误信息
		 */
		if(errors.size() > 0) {
			// 1. 保存错误信息
			// 2. 保存表单数据
			// 3. 转发到regist.jsp
			request.setAttribute("password1", password1);
			request.setAttribute("errors", errors);
			request.setAttribute("form", form);
			return "f:/regist.jsp";
		}
		
		/*
		 * 调用service的regist()方法
		 */
		try {
			userService.regist(form);
		} catch (UserException e) {
			/*
			 * 1. 保存异常信息
			 * 2. 保存form
			 * 3. 转发到regist.jsp
			 */
			request.setAttribute("password1", password1);
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("form", form);
			return "f:/regist.jsp";
		}		
		
		request.setAttribute("msg", "恭喜，注册成功！");
		return "f:/msg.jsp";
	}

	
	public String getCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		String username = request.getParameter("username");
		
		String password = request.getParameter("password");
		
		String password1 = request.getParameter("password1");
		
		String email = request.getParameter("email");
		
		if(email == null || email.trim().isEmpty()) {
			request.setAttribute("username", username);
			request.setAttribute("password", password);
			request.setAttribute("password1", password1);	
			request.setAttribute("email", email);	
			request.setAttribute("emailerror", "Email不能为空！");
			return "f:/regist.jsp";
		} else if(!email.matches("\\w+@\\w+\\.\\w+")) {
			request.setAttribute("username", username);
			request.setAttribute("password", password);
			request.setAttribute("password1", password1);	
			request.setAttribute("email", email);	
			request.setAttribute("emailerror", "Email格式错误！");
			return "f:/regist.jsp";
		}
		
		
		try {
			String code = userService.getCode(email);	
			
			Properties props = new Properties();
			props.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));
			String host = props.getProperty("host");
			String uname = props.getProperty("uname");
			String pwd = props.getProperty("pwd");
			String from = props.getProperty("from");
			String to = email;
			String subject = props.getProperty("subject");
			String content = props.getProperty("content");
			content = MessageFormat.format(content, code);
			Session session = MailUtils.createSession(host, uname, pwd);
			Mail mail = new Mail(from, to, subject, content);
			try {
				MailUtils.send(session, mail);
				request.getSession().setAttribute("code", code);
				request.setAttribute("username", username);
				request.setAttribute("password", password);
				request.setAttribute("password1", password1);	
				request.setAttribute("email", email);	
				return "f:/regist.jsp";
			} catch (MessagingException e) {
				request.getSession().setAttribute("code", code);
				request.setAttribute("username", username);
				request.setAttribute("password", password);
				request.setAttribute("password1", password1);	
				request.setAttribute("email", email);	
				return "f:/regist.jsp";
			}
		} catch (UserException e) {
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("username", username);
			request.setAttribute("password", password);
			request.setAttribute("password1", password1);	
			request.setAttribute("email", email);	
			return "f:/regist.jsp";
		}
	}
	
	public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		User form = CommonUtils.toBean(request.getParameterMap(), User.class);		
		/*
		 * 输入校验
		 * 1. 创建一个Map，用来封装错误信息，其中key为表单字段名称，值为错误信息
		 */
		Map<String,String> errors = new HashMap<String,String>();
		/*
		 * 2. 获取form中的username、password、email进行校验
		 */
		String username = form.getUsername();
		if(username == null || username.trim().isEmpty()) {
			errors.put("username", "用户名不能为空！");
		} else if(username.length() < 3 || username.length() > 10) {
			errors.put("username", "用户名长度必须在3~10之间！");
		}
		
		String password = form.getPassword();
		if(password == null || password.trim().isEmpty()) {
			errors.put("password", "密码不能为空！");
		} else if(password.length() < 3 || password.length() > 10) {
			errors.put("password", "密码长度必须在3~10之间！");
		}
		
		if(errors.size() > 0) {
			// 1. 保存错误信息
			// 2. 保存表单数据
			// 3. 转发到regist.jsp
			request.setAttribute("errors", errors);
			request.setAttribute("form", form);
			return "f:/login.jsp";
		}
		try {
			User user = userService.login(form);
			request.getSession().setAttribute("session_user", user);
			return "r:/study.jsp";
		}catch(UserException e) {
			request.setAttribute("msg",e.getMessage());
			request.setAttribute("form", form);
			return "f:/login.jsp";
		}
	}
	
	public String resetPassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Map<String,String> errors = new HashMap<String,String>();
		/*
		 * 2. 获取form中的username、password、email进行校验
		 */
		String username = (String) request.getAttribute("username");
		if(username == null || username.trim().isEmpty()) {
			errors.put("username", "用户名不能为空！");
		}		
		
		if(errors.size() > 0) {
			// 1. 保存错误信息
			// 2. 保存表单数据
			// 3. 转发到regist.jsp
			request.setAttribute("errors", errors);
			request.setAttribute("username", username); 
			return "f:/resetPassword.jsp";
		}
//		User user = userService.resetPassword();
		return null;
	}
	
	public String exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
		User user = (User)request.getSession().getAttribute("session_user");
		if(user == null) {
			request.setAttribute("msg", "您还没有登录，不能退出！");
		} else {
			request.getSession().removeAttribute("session_user");
			request.setAttribute("msg", "您已退出！");
		}
		return "f:/msg.jsp";
	}
}
